package com.ai.config.easyExcel;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ImageData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.IoUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;

/**
 * @Author jiaok
 * @Date 2025-01-02 16:05
 */
@Slf4j
@Component
public class AlarmRecordImageConverter implements Converter<String> {


    private String defaultAlarmIMG = "static/default_alarm.jpg";

    private ResourceLoader resourceLoader;

    //    @Value("${networkMapping.webServerIp:11.1.168.103}")
    private String webServerIp = "11.1.168.103";

    //    @Value("${networkMapping.webServerMappingIp:10.1.177.51}")
    private String webServerMappingIp = "10.1.177.51";

    //    @Value("${networkMapping.computingPlatform1Ip:11.1.168.104}")
    private String computingPlatform1Ip = "11.1.168.104";

    //    @Value("${networkMapping.computingPlatformMapping1Ip:10.1.177.52}")
    private String computingPlatformMapping1Ip = "10.1.177.52";

    //    @Value("${networkMapping.computingPlatform2Ip:11.1.168.105}")
    private String computingPlatform2Ip = "11.1.168.105";

    //    @Value("${networkMapping.computingPlatformMapping2Ip:10.1.177.53}")
    private String computingPlatformMapping2Ip = "10.1.177.53";


    private byte[] defaultImageBytes;

    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.EMPTY;
    }

    @PostConstruct
    public void init() {
        log.info("===========================  初始化默认图片  ===========================");
        this.defaultImageBytes = loadDefaultImage();
    }

    @Override
    public WriteCellData<?> convertToExcelData(String photoUrl, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        WriteCellData<Void> cellData = new WriteCellData<>();
        cellData.setType(CellDataTypeEnum.EMPTY);

        try {
            if (StrUtil.isEmpty(photoUrl)) {
                log.warn("图片路径为空，使用默认图片");
                byte[] defaultImageBytes = loadDefaultImage();
                setImageData(cellData, defaultImageBytes);
                return cellData;
            }

            // 尝试加载网络图片
            String mappingUrl = getMappingURL(photoUrl);
            photoUrl = mappingUrl;
            URL url = new URL(mappingUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                try (InputStream inputStream = connection.getInputStream()) {
                    byte[] imageBytes = IoUtils.toByteArray(inputStream);
                    log.info("图片加载成功：{}", photoUrl);
                    setImageData(cellData, imageBytes);
                }
            } else {
                log.warn("图片加载失败，响应码：{}，使用默认图片：{}", connection.getResponseCode(), defaultAlarmIMG);
                byte[] defaultImageBytes = loadDefaultImage();
                setImageData(cellData, defaultImageBytes);
            }
        } catch (Exception e) {
            log.error("加载图片失败：{}，使用默认图片", photoUrl.toString(), e);
            byte[] defaultImageBytes = loadDefaultImage();
            setImageData(cellData, defaultImageBytes);
        }
        return cellData;
    }


    /**
     * 获取映射之前的URL
     *
     * @param url 源地址
     * @return 映射之前的url
     * @throws MalformedURLException
     */
    private String getMappingURL(String url) throws MalformedURLException {
        String mappingIp = "";

        URL getPhotoUrl = new URL(url);
        String host = getPhotoUrl.getHost();

        if (host.equals(webServerMappingIp)) {
            mappingIp = webServerIp;
        } else if (host.equals(computingPlatformMapping1Ip)) {
            mappingIp = computingPlatform1Ip;
        } else if (host.equals(computingPlatformMapping2Ip)) {
            mappingIp = computingPlatform2Ip;
        }

        String mappingUrl = url.replace(host, mappingIp);

        return mappingUrl;
    }


    private void setImageData(WriteCellData<Void> cellData, byte[] imageBytes) {
        if (imageBytes == null || imageBytes.length == 0) {
            log.warn("图片字节数组为空，将忽略图片嵌入");
            return;
        }
        ImageData imageData = new ImageData();
        imageData.setImage(imageBytes);
        cellData.setImageDataList(Collections.singletonList(imageData));
    }


    /**
     * 加载默认图片字节数组
     *
     * @return
     */
    public byte[] loadDefaultImage() {
        if (defaultImageBytes == null || defaultImageBytes.length == 0) {
            try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(defaultAlarmIMG)) {
                if (inputStream != null) {
                    defaultImageBytes = IOUtils.toByteArray(inputStream);
                    return defaultImageBytes;
                } else {
                    log.error("加载默认图片失败：文件未找到 - {}", defaultAlarmIMG);
                    return new byte[0];
                }
            } catch (IOException e) {
                log.error("加载默认图片失败：{}", defaultAlarmIMG, e);
                return new byte[0];
            }
        } else {
            return defaultImageBytes;
        }

    }
}
